﻿using CodeMonkey.EditableObject.Core;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;


namespace WpfApplication1.ViewModel
{

	public class ContactViewModel : DynamicViewModel<ContactNew>
	{
		public ContactViewModel(ContactNew contact)
			: base(contact)
		{
			//System.Windows.Markup.XamlReader
			//System.Xaml.XamlReader
			//DataTemplateManager
			
		}
	}

	public class EditableContactViewModel : EditableDynamicViewModel<ContactNew>
	{

		public EditableContactViewModel(ContactNew contact)
			: base(contact)
		{
			ApplyChangesCommand = new RelayCommand(() => { EndEdit(); NotifyUI(); });
			CancelChangesCommand = new RelayCommand(() => { CancelEdit(); });
			NotifyCommand = new RelayCommand(() =>
			{
				NotifyUI();
			}
				);
		}

		public IEnumerable<ValueDescription> SexyList
		{
			get
			{
				return EnumHelper.GetAllValuesAndDescriptions<Sexy>();
			}
		}

		public IEnumerable<ValueDescription> GradeList
		{ get { return EnumHelper.GetAllValuesAndDescriptions<Grade>(); } }

		public RelayCommand ApplyChangesCommand { get; private set; }
		public RelayCommand CancelChangesCommand { get; private set; }

		public RelayCommand NotifyCommand { get; private set; }


		//一律将需要验证的属属性的属性值的获取方法GetPropertyValue<TProperty>(string)方法中的TProperty设置为string
		//用作基准的属性则采用原来的类型
		protected override string ValidateProperty(string prop)
		{
			switch (prop)
			{
				case "FirstName":
					string val = GetPropertyValue<string>(prop); //可能出现泛型类型选择错误;比如把FirstName被认为是int类型;导致基类中转型失败
					if (string.IsNullOrEmpty(val))
					{
						return "FirstName不能为空";
					}
					var d = MainWindow.dd.FirstOrDefault(s => s.FirstName == val && s.ID != GetPropertyValue<int>("ID"));//GetPropertyValue<int>("ID")(() => wrappedObject.ID)
					if (d != null)
					{
						return "不能重复";
					}
					break;
				case "LastName":
					val = GetPropertyValue<string>(prop);
					if (string.IsNullOrEmpty(val))
					{
						return "LastName不能为空";
					}
					break;
				case "Age":
					//double valint = GetPropertyValue<double>(prop);
					string valint = GetPropertyValue<string>(prop);
					double ageNow;
					if (!double.TryParse(valint, out ageNow))
					{
						return "年龄必须是数值";
					}
					if (ageNow < 0)
					{
						return "Age不能小于零";
					}
					if (GetPropertyValue<double>("AgeLarge") <= ageNow) //"AgeLarge"
					{
						return "Age不能大于AgeLarge";
					}
					break;
				default:
					break;
			}
			return string.Empty;
		}
	}
}
